// miniprogram/pages/rule/add.js
Page({
  data: {
    rule: {
      name: '',
      points: '',
      description: ''
    },
    isEdit: false,
    ruleId: null
  },

  onLoad(options) {
    if (options.id) {
      this.setData({
        isEdit: true,
        ruleId: options.id
      })
      this.loadRule(options.id)
    }
  },

  loadRule(id) {
    // 模拟加载规则数据
    const rule = {
      id: id,
      name: '完成家务',
      points: 10,
      description: '完成指定家务任务'
    }
    
    this.setData({
      rule: {
        name: rule.name,
        points: rule.points,
        description: rule.description
      }
    })
  },

  onInput(e) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value
    this.setData({
      [`rule.${field}`]: value
    })
  },

  saveRule() {
    const { name, points, description } = this.data.rule
    
    if (!name) {
      wx.showToast({
        title: '请输入规则名称',
        icon: 'none'
      })
      return
    }
    
    if (!points) {
      wx.showToast({
        title: '请输入积分值',
        icon: 'none'
      })
      return
    }
    
    // 模拟保存操作
    wx.showToast({
      title: this.data.isEdit ? '更新成功' : '添加成功',
      icon: 'success'
    })
    
    setTimeout(() => {
      wx.navigateBack()
    }, 1500)
  },

  deleteRule() {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条积分规则吗？',
      success: (res) => {
        if (res.confirm) {
          // 模拟删除操作
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          })
          
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        }
      }
    })
  }
})